package com.concurrent.sample.business.service.impl;

import com.concurrent.sample.business.entity.EventEntity;
import com.concurrent.sample.business.dto.debug.AppDebugInfoDTO;
import com.concurrent.sample.business.dto.debug.DataMemoryTypeEnum;
import com.concurrent.sample.business.repo.EventRepo;
import com.concurrent.sample.business.service.EventService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Slf4j
public class EventServiceImpl implements EventService {

  public static Map<Long, EventEntity> ID_CONTAINER = new HashMap<>();

  private static AtomicLong idAtomic = new AtomicLong(0);

  private final EventRepo eventRepo;

  @Transactional(rollbackFor = Exception.class)
  @Override
  public void save(List<EventEntity> eventEntities) {
    if(AppDebugInfoDTO.dataMemoryType == DataMemoryTypeEnum.LOCAL){
      for (EventEntity eventEntity : eventEntities){
        eventEntity.setId(idAtomic.incrementAndGet());
        ID_CONTAINER.put(eventEntity.getId(), eventEntity);
      }
    } else {
      eventRepo.saveAll(eventEntities);
    }
  }

  @Override
  public EventEntity getById(Long id) {
    if(AppDebugInfoDTO.dataMemoryType == DataMemoryTypeEnum.LOCAL){
      return ID_CONTAINER.get(id);
    } else {
      return eventRepo.findById(id).orElse(null);
    }
  }

}
